package com.sunyard.client2;

import com.irdstudio.efp.edoc.service.bo.UpLoadFileVO;
import com.sunyard.client.SunEcmClientApi;
import com.sunyard.client.bean.*;
import com.sunyard.client.impl.SunEcmClientSocketApiImpl;
import com.sunyard.client2.util.StringUtil;
import com.sunyard.ecm.server.bean.*;
import com.sunyard.util.OptionKey;
import com.sunyard.util.TransOptionKey;
import com.sunyard.ws.utils.XMLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 客户端使用示例
 * 
 * @author Warren
 * 
 */
public class Client {
	private static Logger logger = LoggerFactory.getLogger(Client.class);

	public static String ip;
	public static int socketPort;

	public static String userName;
	public static String passWord;
	public static String downFile;
	public static String downFilePath;
	public static String organNo;
	public volatile static boolean isInit = false;
	//影像类型分隔符
	private final static String IMAGE_TYPE_SEPERATOR = "_";

	public static SunEcmClientApi clientApi;

	public static String url;
	public static int httpPort;

	public static void init() {
		// 获取配置文件
		try {
			ResourceBundle res = ResourceBundle.getBundle("client");
 			ip = res.getString("ip");
			socketPort = Integer.parseInt(res.getString("socketPort"));
			userName = res.getString("userName");
			passWord = res.getString("passWord");
			downFilePath = res.getString("downFilePath");
			organNo = res.getString("organNo");
			url = res.getString("url");
			httpPort = Integer.parseInt(res.getString("httpPort"));
			isInit = true;
			clientApi = new SunEcmClientSocketApiImpl(ip, socketPort, false);
		} catch (Exception e) {
			logger.error("获取影像平台配置信息出错！" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 登录
	 * 
	 * @param userName
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 * @throws Exception
	 */
	public static void login() {
		try {
			if (!isInit) {
				init();
			}
			String resultMsg = clientApi.login(userName, passWord);
			logger.info("#######登录返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######登录失败#######" + e.getMessage());
            e.printStackTrace();
		}
	}

	/**
	 * 登出
	 * 
	 * @param userName
	 *            用户名密码
	 * @return
	 * @throws Exception
	 */
	public static void logout() {
		try {
			if (!isInit) {
				init();
			}
			String resultMsg = clientApi.logout(userName);
			logger.info("#######登出返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######登出失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 检出----------------------------------------------------------------------
	 * 
	 * @return
	 * @throws Exception
	 */
	public void checkOut(String id, String modelCode, String startColumn, String startDate) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(modelCode);
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.getIndex_Object().addCustomMap(startColumn, startDate);
		clientBatchBean.getIndex_Object().setContentID(id);

		try {
			String checkToken = clientApi.checkOut(clientBatchBean, null);
			String[] result = checkToken.split("<<::>>");
			checkToken = result[1];
			logger.info("#######检出返回的信息[" + checkToken + "]#######");
		} catch (Exception e) {
			logger.error("#######检出失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 检入---------------------------------------------------------------------- --
	 * 
	 * @return
	 * @throws Exception
	 */
	public void checkIn(String modelCode, String startColumn, String startDate, String contentID) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(modelCode);
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.getIndex_Object().addCustomMap(startColumn, startDate);
		clientBatchBean.getIndex_Object().setContentID(contentID);
		// clientBatchBean.setCheckToken(checkToken);
		try {
			String resultMsg = clientApi.checkIn(clientBatchBean, null);
			logger.info("#######检入返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######检入失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 上传接口调用示例 -------------------------------------------------------
	 */
	public static String uploadExample(BaseBean baseBean) {
		if (!isInit) {
			init();
		}
		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setUser(userName); //用户名
		clientBatchBean.setPassWord(passWord); //密码
		clientBatchBean.setModelCode(baseBean.getModelCode()); //内容模型代码
		clientBatchBean.setBreakPoint(false); // 是否作为断点续传上传
		clientBatchBean.setOwnMD5(false); // 是否为批次下的文件添加MD5码
		clientBatchBean.setBATCH_DATE(baseBean.getBatchDate());// 批次日期
		clientBatchBean.setMACHINE_NUM(baseBean.getMachineNum());// 机器码
		clientBatchBean.setSERIAL_NUM(baseBean.getApplySeq());// 流水号
		/** @date 2019/03/29 @author qiuyf @describe 机构号 */
		clientBatchBean.setORGAN_NO(organNo); 
		
		// =========================设置索引对象信息开始=========================
		ClientBatchIndexBean clientBatchIndexBean = new ClientBatchIndexBean();
		// 索引自定义属性
		clientBatchIndexBean.addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());
		/** @date 2019/03/29 @author qiuyf 流水号 */
		clientBatchIndexBean.addCustomMap(FileAttrConstant.BUSI_SERIAL_NO, baseBean.getApplySeq()); 
		/** @date 2019/03/29 @author qiuyf @describe 客户证件号码  */
		clientBatchIndexBean.addCustomMap(FileAttrConstant.IDENTITY, baseBean.getCertCode()); 
		
		/** @date 2019/04/03 @author qiuyf @describe 客户名称  */
		clientBatchIndexBean.addCustomMap(FileAttrConstant.CUSTOMER, baseBean.getCusName());  
		/** @date 2019/04/03 @author qiuyf @describe 产品名称 */
		clientBatchIndexBean.addCustomMap(FileAttrConstant.PRD_NAME, baseBean.getPrdName()); 
		
		// =========================设置文档部件信息开始=========================
		ClientBatchFileBean clientBatchFileBean = new ClientBatchFileBean();
		clientBatchFileBean.setFilePartName(baseBean.getFilePartName());
		// =========================设置文档部件信息结束=========================
		// =========================添加文件=========================
		File path = new File(baseBean.getUrlFile());
		File[] files = path.listFiles();
		if(null == files || files.length == 0) {
			return "路径下："+baseBean.getUrlFile()+"，不存在文件信息！";
		}
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				continue;
			}
			ClientFileBean fileBean = new ClientFileBean();
			fileBean.setFileName(files[i].getAbsolutePath());
			// 获取文件类型（文件名后缀）
			fileBean.setFileFormat(files[i].getName().substring(files[i].getName().lastIndexOf(".") + 1));
			fileBean.setFilesize(String.valueOf(files[i].length()));
			// 文件属性值
			String dateFile = files[i].getName().substring(files[i].getName().indexOf("_") + 1, files[i].getName().lastIndexOf("."));
			if(!FileNameEnums.map.containsKey(dateFile)){
				for (Map.Entry<String,String> m : FileNameEnums.map.entrySet()){
					if(!com.irdstudio.basic.framework.core.util.StringUtil.isNullorBank(dateFile) && dateFile.endsWith(m.getKey())){
						dateFile = m.getKey();
						break;
					}
				}
			}
			if (StringUtil.isNull(dateFile)) {
				dateFile = "unkonw";
			}
			fileBean.addOtherAtt(baseBean.getSignFile(), FileNameEnums.map.get(dateFile));
			/** @date 2019/03/29 @author qiuyf  @describe 文件描述  */
			fileBean.addOtherAtt(FileAttrConstant.FILE_INFO, FileNameEnums.mapImage.get(FileNameEnums.map.get(dateFile))); 
			/**
			 * 影像平台改造，为了网贷系统通过页面拼接URL的方式，访问到对应API上传的影像信息
			 * 【变更内容】：
			 * 		1. 页码 (BUSI_FILE_PAGENUM)
			 *      2. 目录树节点 (BUSI_FILE_TYPE)
			 *      3. 扫描人 (BUSI_FILE_SCANUSER)
			 *      4. 文件中文名称 (FILE_CN_NAME)
			 *      5. 图片的扫描参数 (EXIF)
			 *      6. 文件个数 (AMOUNT)
			 * @date 2019/05/05
			 * @author qiuyf
			 */
			// 页码（上传批次中包含的第一个文件为页码1，第二个文件为页码2，如此类推...）
			fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_PAGENUM, String.valueOf(i + 1));
			// 目录树节点
			fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_TYPE, FileNameEnums.mapRootNode.get(FileNameEnums.map.get(dateFile)));
			// 扫描人（赋值登录用户名）
			fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_SCANUSER, userName);
			// 文件中文名称
			fileBean.addOtherAtt(FileAttrConstant.FILE_CN_NAME, FileNameEnums.mapImage.get(FileNameEnums.map.get(dateFile)));
			// 图片的扫描参数（目前影像文件是读取存放在文件夹中的文件信息，不是扫描文件，所以填写空字符串）
			fileBean.addOtherAtt(FileAttrConstant.EXIF, "");
			
			clientBatchFileBean.addFile(fileBean);
		}
		// 上传文件数
		clientBatchIndexBean.setAmount(String.valueOf(files.length));
		// 上传文件个数
		clientBatchIndexBean.addCustomMap(FileAttrConstant.AMOUNT, String.valueOf(files.length));
		
		// =========================添加文件=========================
		clientBatchBean.setIndex_Object(clientBatchIndexBean); // 让批次对象关联上面的clientBatchFileBean批次索引对象
		clientBatchBean.addDocument_Object(clientBatchFileBean); // 批次对象关联这次封装了上传文件的批次文件对象Bean
		
		long start = System.currentTimeMillis();
		String resultMsg = "";
		try {
			String str = XMLUtil.bean2XML(clientBatchBean);
			logger.info("#######上传批次XML=========[" + str + "]#######");
			
			resultMsg = clientApi.upload(clientBatchBean, null);
			
			logger.info("#######上传批次返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("===============上传影像信息失败，上传流水号："+baseBean.getApplySeq()+"批次号："+clientBatchBean.getIndex_Object().getContentID(), e.getMessage());
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		long times = end - start;
		logger.info("#######上传一个批次需要的时间：" + times + "#######");
		return resultMsg;
	}

	/**
	 * 需求编号：2019D0519<br/>
	 * 问题编号：<br/>
	 * 功能描述：更新或追加同一个批次中的单个文件<br/>
	 * 开发人员：周才顺<br/>
	 * 创建时间：2019年5月23日 下午4:59:40<br/>
	 * @author zhoucs1
	 * @since  1.0
	 * @version 1.0
	 * @param baseBean
	 * @return
	 */
	public static String updateSingleFile(BaseBean baseBean, UpLoadFileVO upLoadFileVO) throws Exception{
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(baseBean.getModelCode());
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setOwnMD5(false);
		clientBatchBean.setBATCH_DATE(baseBean.getBatchDate());// 批次日期
		clientBatchBean.setMACHINE_NUM(baseBean.getMachineNum());// 机器码
		clientBatchBean.setSERIAL_NUM(baseBean.getApplySeq());// 流水号
		clientBatchBean.getIndex_Object().setContentID(baseBean.getContentId());
		clientBatchBean.getIndex_Object().addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());

		ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
		batchFileBean.setFilePartName(baseBean.getFilePartName());
		// =========================添加文件=========================
		File path = new File(baseBean.getUrlFile());
		ClientFileBean fileBean = new ClientFileBean();
		fileBean.setOptionType(OptionKey.U_ADD);// 操作类型为追加
		fileBean.setFileName(path.getAbsolutePath());
		fileBean.setFileFormat(path.getName().substring(path.getName().lastIndexOf(".") + 1));
		fileBean.addOtherAtt(baseBean.getSignFile(), upLoadFileVO.getImageType());
		batchFileBean.addFile(fileBean);

		clientBatchBean.addDocument_Object(batchFileBean);
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######更新批次XML=========[" + str + "]#######");
		String resultMsg = "";
		try {
			resultMsg = clientApi.update(clientBatchBean, null, true);
			logger.info("#######更新批次追加文件返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######更新批次追加文件失败[" + resultMsg + "]#######" + e.getMessage());
			e.printStackTrace();
			throw new Exception("访问影像系统时出现异常,异常信息为：" + e.getMessage());
		}
		return resultMsg;
	}

	/**
	 * 上传通过校验的list中的所有文件<br/>
	 * @author zhoucs1
	 * @since  2019年4月25日 下午3:36:55
	 * @param baseBean
	 * @param uploadFileList
	 * @return
	 */
	public static String uploadListFiles(BaseBean baseBean, List<UpLoadFileVO> uploadFileList) throws Exception {
		if (!isInit) {
			init();
		}
		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setModelCode(baseBean.getModelCode());
		clientBatchBean.setBreakPoint(false); // 是否作为断点续传上传
		clientBatchBean.setOwnMD5(false); // 是否为批次下的文件添加MD5码
		clientBatchBean.setBATCH_DATE(baseBean.getBatchDate());// 批次日期
		clientBatchBean.setMACHINE_NUM(baseBean.getMachineNum());// 机器码
		clientBatchBean.setSERIAL_NUM(baseBean.getApplySeq());// 流水号
		// =========================设置索引对象信息开始=========================
		ClientBatchIndexBean clientBatchIndexBean = new ClientBatchIndexBean();
		// 索引自定义属性
		clientBatchIndexBean.addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());
		// =========================设置文档部件信息开始=========================
		ClientBatchFileBean clientBatchFileBean = new ClientBatchFileBean();
		clientBatchFileBean.setFilePartName(baseBean.getFilePartName());
		// =========================设置文档部件信息结束=========================
		// =========================添加文件=========================
		for (UpLoadFileVO upLoadFileVO : uploadFileList) {
			//获取文件地址
			String filePath = upLoadFileVO.getFilePath();
			File file = new File(filePath);

			ClientFileBean fileBean = new ClientFileBean();
			fileBean.setFileName(file.getAbsolutePath());
			fileBean.setFileFormat(file.getName().substring(file.getName().lastIndexOf(".") + 1));
			fileBean.setFilesize(String.valueOf(file.length()));
			//设置影像类型
			fileBean.addOtherAtt(baseBean.getSignFile(), upLoadFileVO.getImageType());
			clientBatchFileBean.addFile(fileBean);
		}
		// 上传文件数
		clientBatchIndexBean.setAmount(String.valueOf(uploadFileList.size()));
		// =========================添加文件=========================
		clientBatchBean.setIndex_Object(clientBatchIndexBean);
		clientBatchBean.addDocument_Object(clientBatchFileBean);
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######上传批次XML=========[" + str + "]#######");
		long start = System.currentTimeMillis();
		String resultMsg = "";
		try {
			resultMsg = clientApi.upload(clientBatchBean, null);
			logger.info("#######上传批次返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("===============上传失败============" + clientBatchBean.getIndex_Object().getContentID()
					+ e.getMessage());
			e.printStackTrace();
			throw new Exception("访问影像系统时出现异常,异常信息为：" + e.getMessage());
		}
		long end = System.currentTimeMillis();
		long times = end - start;
		logger.info("#######上传一个批次需要的时间：" + times + "#######");
		return resultMsg;
	}
	/**
	 * 查询接口调用示例 -------------------------------------------------------
	 */
	public static String queryExample(BaseBean baseBean) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(baseBean.getModelCode()); //内容模型
		/** @date 2019/03/29 @author qiuyf @describe 机构号 */
		clientBatchBean.setORGAN_NO(organNo); 
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setDownLoad(true);
		clientBatchBean.getIndex_Object().setVersion("0");// 0为最新版本
		clientBatchBean.getIndex_Object().setContentID(baseBean.getContentId());
		clientBatchBean.getIndex_Object().addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());

		// 若内容模型配置有安全校验
		// clientBatchBean.setToken_check_value(token_check_value);
		// clientBatchBean.setToken_code("D5886B4F1D0DCC811EB11A8EA81DEE31");

		ClientBatchFileBean documentObject = new ClientBatchFileBean();
		documentObject.setFilePartName(baseBean.getFilePartName()); // 要查询的文档部件名
		if (StringUtil.isNotNull(baseBean.getDataFile())) {
			documentObject.addFilter(baseBean.getSignFile(), baseBean.getDataFile()); // 增加过滤条件(查询单个文件)
		}
		clientBatchBean.addDocument_Object(documentObject);
		
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######查询批次XML=========[" + str + "]#######");
		String resultMsg = "";
		try {
			resultMsg = clientApi.queryBatch(clientBatchBean, null);
			logger.info("#######查询批次返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######查询批次失败[" + resultMsg + "]#######" + e.getMessage());
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 高级搜索调用示例 -------------------------------------------------------
	 * 最后结果为组上最大版本的批次号
	 */
	public void heightQueryExample(String modelCode, String startColumn, String startDate) {
		if (!isInit) {
			init();
		}

		ClientHeightQuery heightQuery = new ClientHeightQuery();
		heightQuery.setUserName(userName);
		heightQuery.setPassWord(passWord);
		heightQuery.setLimit(10);
		heightQuery.setPage(1);
		heightQuery.setModelCode(modelCode);
		heightQuery.addCustomAtt(startColumn, startDate);
		// heightQuery.addCustomAtt("BUSI_SERIAL_NO", "2013092701");
		// heightQuery.addfilters("VARCHARTYPE='varchartype'");
		
		String str = XMLUtil.bean2XML(heightQuery);
		logger.info("#######高级搜索批次XML=========[" + str + "]#######");
		
		try {
			String resultMsg = clientApi.heightQuery(heightQuery, null);
			logger.info("#######调用高级搜索返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######高级搜索失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 删除接口调用示例 -------------------------------------------------------
	 */
	public static String deleteExample(BaseBean baseBean) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(baseBean.getModelCode()); //内容模型
		/** @date 2019/03/29 @author qiuyf @describe 机构号 */
		clientBatchBean.setORGAN_NO(organNo);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setUser(userName);
		clientBatchBean.getIndex_Object().setContentID(baseBean.getContentId());
		clientBatchBean.getIndex_Object().addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());
		
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######删除批次XML=========[" + str + "]#######");
		String resultMsg = "";
		try {
			resultMsg = clientApi.delete(clientBatchBean, null);
			logger.info("#######删除批次返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######删除批次失败#######" + e.getMessage());
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 更新追加一个批次的单个文件
	 * 
	 */
	public static String updateExample(BaseBean baseBean) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(baseBean.getModelCode()); //内容模型
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setOwnMD5(false); //文件传输不需要MD5的校验
		clientBatchBean.setBATCH_DATE(baseBean.getBatchDate());// 批次日期
		clientBatchBean.setMACHINE_NUM(baseBean.getMachineNum());// 机器码
		clientBatchBean.setSERIAL_NUM(baseBean.getApplySeq());// 流水号
		/** @date 2019/03/29 @author qiuyf @describe 机构号 */
		clientBatchBean.setORGAN_NO(organNo); 
		clientBatchBean.getIndex_Object().setContentID(baseBean.getContentId());
		clientBatchBean.getIndex_Object().addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());

		ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
		batchFileBean.setFilePartName(baseBean.getFilePartName());
		// =========================添加文件=========================
		File path = new File(baseBean.getUrlFile());
		ClientFileBean fileBean = new ClientFileBean();
		fileBean.setOptionType(OptionKey.U_ADD);// 操作类型为追加
		
		logger.info("追加文件到影像系统上传文件参数:" + baseBean.toString());
		fileBean.setFileName(path.getAbsolutePath());
		fileBean.setFileFormat(path.getName().substring(path.getName().lastIndexOf(".") + 1));
		String dateFile = path.getName().substring(path.getName().indexOf("_") + 1, path.getName().lastIndexOf("."));// 文件属性值
		Pattern p = Pattern.compile(".*\\d+.*");
		Matcher m = p.matcher(dateFile);
		if (m.matches()) {// 包含数字，为保单
			dateFile = "unkonw";
		}
		
		fileBean.addOtherAtt(baseBean.getSignFile(), FileNameEnums.map.get(dateFile));
		/** @date 2019/03/29 @author qiuyf  @describe 文件描述  */
		fileBean.addOtherAtt(FileAttrConstant.FILE_INFO, FileNameEnums.mapImage.get(FileNameEnums.map.get(dateFile)));

		//影像平台改造，为了网贷系统通过页面拼接URL的方式，访问到对应API上传的影像信息
		String ret = queryExample(baseBean);
		//查询查询当前批次上传的信息
		Map<String, String> batchFileInfoMap = getUpdateBatchFileInfo(ret);
		if(batchFileInfoMap == null) {
			return "";
		}
		// =========================设置索引对象信息开始=========================
		//流水号
		fileBean.addOtherAtt(FileAttrConstant.BUSI_SERIAL_NO, batchFileInfoMap.get(FileAttrConstant.BUSI_SERIAL_NO));
		//流水号生成时间
		fileBean.addOtherAtt(FileAttrConstant.BUSI_START_DATE, batchFileInfoMap.get(FileAttrConstant.BUSI_START_DATE));
		//客户证件号码
		fileBean.addOtherAtt(FileAttrConstant.IDENTITY, batchFileInfoMap.get(FileAttrConstant.IDENTITY));
		//客户名称
		fileBean.addOtherAtt(FileAttrConstant.CUSTOMER, batchFileInfoMap.get(FileAttrConstant.CUSTOMER));
		//产品名称
		fileBean.addOtherAtt(FileAttrConstant.PRD_NAME, batchFileInfoMap.get(FileAttrConstant.PRD_NAME));
		// =========================设置索引对象信息结束=========================

		//查询当前批次的最大的页码
		int pageNum = getBusiFilePageNum(ret);
		if(pageNum < 1) {
			return "";
		}
		pageNum++;
		// 页码（上传批次中包含的第一个文件为页码1，第二个文件为页码2，如此类推...）
		fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_PAGENUM, String.valueOf(pageNum));
		// 目录树节点
		fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_TYPE, FileNameEnums.mapRootNode.get(FileNameEnums.map.get(dateFile)));
		// 扫描人（赋值登录用户名）
		fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_SCANUSER, userName);
		// 文件中文名称
		fileBean.addOtherAtt(FileAttrConstant.FILE_CN_NAME, FileNameEnums.mapImage.get(FileNameEnums.map.get(dateFile)));
		// 图片的扫描参数（目前影像文件是读取存放在文件夹中的文件信息，不是扫描文件，所以填写空字符串）
		fileBean.addOtherAtt(FileAttrConstant.EXIF, "");
		batchFileBean.addFile(fileBean);

		// 修改文档部件字段
		// ClientFileBean clientFileBean = new ClientFileBean();
		// clientFileBean.setOptionType(OptionKey.U_MODIFY);
		// clientFileBean.setFileNO("1E20EBFF-A793-D087-C033-D4236EDCF5F4");
		// clientFileBean.addOtherAtt(STARTCOLUMN, "20140817");
		// batchFileBean.addFile(clientFileBean);
		clientBatchBean.addDocument_Object(batchFileBean);
		
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######更新追加一个批次的单个文件XML=========[" + str + "]#######");
		String resultMsg = "";
		try {
			resultMsg = clientApi.update(clientBatchBean, null, true);
			logger.info("#######更新批次追加文件返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######更新批次追加文件失败[" + resultMsg + "]#######" + e.getMessage());
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 更新替换一个批次的单个文件
	 * 
	 */
	public static String updateReplaceExample(BaseBean baseBean,String fileNo) {
		if (!isInit) {
			init();
		}
		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(baseBean.getModelCode());
		/** @date 2019/03/29 @author qiuyf @describe 机构号 */
		clientBatchBean.setORGAN_NO(organNo); 
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setOwnMD5(false);
		clientBatchBean.getIndex_Object().setContentID(baseBean.getContentId());
		clientBatchBean.getIndex_Object().addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());

		ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
		batchFileBean.setFilePartName(baseBean.getFilePartName());

		ClientFileBean fileBean = new ClientFileBean();
		fileBean.setOptionType(OptionKey.U_REPLACE); //操作类型为替换文件
		fileBean.setFileNO(fileNo); //替换文件ID
		File path = new File(baseBean.getUrlFile());
		fileBean.setFileName(path.getAbsolutePath());
		fileBean.setFileFormat(path.getName().substring(path.getName().lastIndexOf(".") + 1));
		String dateFile = path.getName().substring(path.getName().indexOf("_") + 1, path.getName().lastIndexOf("."));// 文件属性值
		Pattern p = Pattern.compile(".*\\d+.*");
		Matcher m = p.matcher(dateFile);
		if (m.matches()) {// 包含数字，为保单
			dateFile = "unkonw";
		}
		/** @date 2019/03/29 @author qiuyf  @describe 文件描述  */
		fileBean.addOtherAtt(FileAttrConstant.FILE_INFO, FileNameEnums.mapImage.get(FileNameEnums.map.get(dateFile)));
		batchFileBean.addFile(fileBean);
		clientBatchBean.addDocument_Object(batchFileBean);
		
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######更新替换一个批次的单个文件XML=========[" + str + "]#######");
		String resultMsg = "";
		try {
			resultMsg = clientApi.update(clientBatchBean, null, true);
			logger.info("#######更新批次替换文件返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######更新批次替换文件失败[" + resultMsg + "]#######" + e.getMessage());
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 更新删除一个批次的单个文件
	 * 
	 */
	public static String updateDelExample(BaseBean baseBean,String fileNo) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(baseBean.getModelCode());
		/** @date 2019/03/29 @author qiuyf @describe 机构号 */
		clientBatchBean.setORGAN_NO(organNo);
		clientBatchBean.setUser(userName);
		clientBatchBean.setPassWord(passWord);
		clientBatchBean.setOwnMD5(false);
		clientBatchBean.getIndex_Object().setContentID(baseBean.getContentId());
		clientBatchBean.getIndex_Object().addCustomMap(baseBean.getStartColumn(), baseBean.getStartDate());

		ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
		batchFileBean.setFilePartName(baseBean.getFilePartName());
		ClientFileBean fileBean = new ClientFileBean();
		fileBean.setOptionType(OptionKey.U_DEL); //操作类型为删除文件
		fileBean.setFileNO(fileNo); //文件ID
		batchFileBean.addFile(fileBean);
		clientBatchBean.addDocument_Object(batchFileBean);
		
		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######更新删除一个批次的单个文件XML=========[" + str + "]#######");
		String resultMsg = "";
		try {
			resultMsg = clientApi.update(clientBatchBean, null, true);
			logger.info("#######更新批次删除文件返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######更新批次删除文件失败[" + resultMsg + "]#######" + e.getMessage());
			e.printStackTrace();
		}
		return resultMsg;
	}

	/**
	 * 新增批注
	 * 
	 * @throws Exception
	 */
	public void operAnnotation(String modelCode, String filePartName, String contentID, String annoID) {
		if (!isInit) {
			init();
		}

		// 设定批次信息
		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(modelCode);
		clientBatchBean.setUser(userName);
		clientBatchBean.getIndex_Object().addCustomMap("BUSI_START_DATE", "20120929");
		clientBatchBean.getIndex_Object().setContentID(contentID);
		// 若内容模型配置有安全校验
		// clientBatchBean.setToken_check_value(token_check_value);
		// clientBatchBean.setToken_code(tokenCode);
		// 设定文档部件信息
		ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
		batchFileBean.setFilePartName(filePartName);

		// 设定文件信息
		ClientFileBean clientFileBean = new ClientFileBean();
		clientFileBean.setFileNO("1BF8004E-957F-EE07-20E3-D6066AF85B99");

		// 追加批注信息
		ClientAnnotationBean annotationBean = new ClientAnnotationBean();
		annotationBean.setAnnotation_id(annoID);
		annotationBean.setAnnotation_flag(OptionKey.U_ADD);
		annotationBean.setAnnotation_x1pos("1");
		annotationBean.setAnnotation_y1pos("1");
		annotationBean.setAnnotation_x2pos("100");
		annotationBean.setAnnotation_y2pos("5");
		annotationBean.setAnnotation_content("内容模型批注");
		annotationBean.setAnnotation_color("red");

		clientFileBean.addAnnoList(annotationBean); // 批注关联文件
		batchFileBean.addFile(clientFileBean); // 文件关联文档部件
		clientBatchBean.addDocument_Object(batchFileBean); // 文档部件关联批次

		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######新增批注XML=========[" + str + "]#######");
		try {
			String resultMsg = clientApi.operAnnotation(clientBatchBean, null);
			logger.info("#######新增批注返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######新增批注失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 查询批注
	 * 
	 * @throws Exception
	 */
	public void queryAnnotation(String modelCode, String filePartName, String contentID, String fileNo) {
		if (!isInit) {
			init();
		}

		ClientBatchBean clientBatchBean = new ClientBatchBean();
		clientBatchBean.setModelCode(modelCode);
		clientBatchBean.setUser(userName);
		// clientBatchBean.getIndex_Object().setVersion("1");
		clientBatchBean.getIndex_Object().addCustomMap("START_TIME", "20120612");
		clientBatchBean.getIndex_Object().setContentID(contentID);

		// 若内容模型配置有安全校验
		// clientBatchBean.setToken_check_value(token_check_value);
		// clientBatchBean.setToken_code(tokenCode);

		// 设定文档部件信息
		ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
		batchFileBean.setFilePartName(filePartName);

		// 设定文件信息
		ClientFileBean clientFileBean = new ClientFileBean();
		clientFileBean.setFileNO(fileNo);

		batchFileBean.addFile(clientFileBean); // 文件关联文档部件
		clientBatchBean.addDocument_Object(batchFileBean); // 文档部件关联批次

		String str = XMLUtil.bean2XML(clientBatchBean);
		logger.info("#######查询批注XML=========[" + str + "]#######");
		try {
			String resultMsg = clientApi.queryAnnotation(clientBatchBean, null);
			logger.info("#######查询批注返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######查询批注失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 客户端获得内容模型权限获取 -------------------------------------------------------
	 */
	public void getPermissions_Client() {
		if (!isInit) {
			init();
		}

		try {
			String resultMsg = clientApi.getPermissions_Client(userName, passWord);
			logger.info("#######客户端获得内容模型权限获取返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######客户端获得内容模型权限获取失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 客户端获取所有服务器信息
	 * 
	 */
	public void getContentServerInfo_Client() {
		if (!isInit) {
			init();
		}

		try {
			String resultMsg = clientApi.getContentServerInfo_Client();
			logger.info("#######客户端获取所有服务器返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######客户端获取所有服务器失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 客户端获得获取内容模型列表信息
	 */
	public void getAllModelMsg_Client() {
		if (!isInit) {
			init();
		}

		try {
			String resultMsg = clientApi.getAllModelMsg_Client();
			logger.info("#######客户端获得获取内容模型列表返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######客户端获得获取内容模型列表失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 客户端获取内容模型模版
	 */
	public void getModelTemplate_Client(String modelCode) {
		if (!isInit) {
			init();
		}

		String[] modeCodes = { modelCode };
		try {
			String resultMsg = clientApi.getModelTemplate_Client(modeCodes);
			logger.info("#######客户端获取内容模型模版返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######客户端获取内容模型模版失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 客户端获取内容存储服务器信息
	 */
	public void inquireDMByGroup() {
		if (!isInit) {
			init();
		}

		try {
			String resultMsg = clientApi.inquireDMByGroup(userName, null);
			logger.info("#######客户端获取内容存储服务器信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######客户端获取内容存储服务器信息失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 客户端获取令牌，调用WEBSERVICE
	/*
	 * public void getToken() { try { String oper = OperPermission.ADD + "," +
	 * OperPermission.UPD + "," + OperPermission.DEL + "," + OperPermission.QUY +
	 * "," + OperPermission.MAK;
	 * 
	 * String resultMsg = clientApi.getToken(
	 * "http://172.16.3.242:9080/SunECMConsole", token_check_value, userName, oper);
	 * logger.info("#######客户端获取令牌返回的信息[" + resultMsg + "]#######"); } catch
	 * (Exception e) { e.printStackTrace(); } }
	 */

	public static void receiveFileByURL(String urlStr, String systemType, String fileName) {
		if (!isInit) {
			init();
		}
		File file = new File(downFilePath + systemType + fileName);
		URL url;
		InputStream in = null;
		try {
			url = new URL(urlStr);
			in = url.openStream();
			@SuppressWarnings("resource")
			FileOutputStream fos = new FileOutputStream(file);
			if (in != null) {
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					fos.write(b, 0, len);
				}
			}
		} catch (FileNotFoundException e) {
			logger.error("#######http下载失败#######" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("#######http下载失败#######" + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				logger.error("#######http下载失败#######" + e.getMessage());
				e.printStackTrace();
			}
		}
	}


	/**
	 * 根据请求url下载文件存放到路径
	 * @param fileUrl
	 * @param savePath
	 * @throws Exception
	 */
	public static void downLoanFile(String fileUrl, String savePath) throws Exception {

		InputStream in=null;
		FileOutputStream fos=null;
		try {
			if (!isInit) {
				init();
			}
			File file = new File(downFile + savePath);

			logger.info("根据请求url下载文件存放到路径:url="+fileUrl+"######保存路径为"+downFile+savePath);

			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}

			URL url = new URL(fileUrl);
			in = url.openStream();
			fos = new FileOutputStream(file);

			if (in != null) {
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					fos.write(b, 0, len);
				}
			}
		} finally {
			if (fos!=null) {
				fos.close();
			}
			if (in != null) {
				in.close();
			}
		}

	}

	/**
	 * 客户端调用立即迁移接口 -------------------------------------------------------
	 */
	public void immedMigrate(String batchId, String modelCode, String startColumn, String startDate) {
		if (!isInit) {
			init();
		}

		MigrateBatchBean m = new MigrateBatchBean();
		m.setMigrate(true);
		m.setModelCode(modelCode);
		m.setUser(userName);
		m.setPassWord(passWord);
		m.getIndex_Object().setContentID(batchId);
		m.getIndex_Object().addCustomMap(startColumn, startDate);
		try {
			String resultMsg = clientApi.immedMigrate(m, null);
			logger.info("#######客户端调用立即迁移返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######客户端调用立即迁移失败#######" + e.getMessage());
			e.printStackTrace();
		}
	}

	public void queryNodeInfoByGroupIdAndInsNo() {
		if (!isInit) {
			init();
		}

		try {
			String resultMsg = clientApi.queryNodeInfoByGroupIdAndInsNo("FTC_IDX", "jigou");
			logger.info("#######返回的信息[" + resultMsg + "]#######");
		} catch (Exception e) {
			logger.error("#######返回失败#######" + e.getMessage());
			e.printStackTrace();
		}

	}

	// 多线程客户端
	@SuppressWarnings("unused")
	private Runnable createTask(final int taskID) {
		return new Runnable() {
			public void run() {
				logger.info("#######现在进行第[" + taskID + "]个任务#######");
				// getToken();
				// checkOut(); //88d29fee522dbf173337
				// login();
				for (int i = 0; i < 5; i++) {
					// uploadExample();
				}
				// checkIn();

				// queryAndDownload();

				// immedMigrate(contentID);
				// inquireDMByGroup();
				// heightQueryExample();
				// login();
				// queryExample(contentID);
				// operAnnotation();
				// queryAnnotation();
				// deleteExample();
				// getAllModelMsg_Client();
				// getContentServerInfo_Client();
				// getModelTemplate_Client();
				// getPermissions_Client();
				// logout();

				// queryNodeInfoByGroupIdAndInsNo();
				// System.out.println("测试完成");
			}
		};
	}

	/**
	 *
	 * 查询当前批次的最大的页码 <br>
	 * 0.1:ludayong:2019年8月30日 上午10:21:38:新增 <br>
	 *
	 * @author ludayong
	 * @since 2019年8月30日 上午10:21:38
	 * @date 2019年8月30日 上午10:21:38
	 * @version 0.1
	 */
	public static int getBusiFilePageNum(String resultMsg) {
		// 页码
		int busiFilePageNum = 0;
		try {
			if (Objects.nonNull(resultMsg) && !"".equals(resultMsg)) {
				String batchStr = resultMsg.split(TransOptionKey.SPLITSYM)[1];
				List<BatchBean> batchBeans = XMLUtil.xml2list(XMLUtil.removeHeadRoot(batchStr), BatchBean.class);
				for (BatchBean batchBean : batchBeans) {
					List<BatchFileBean> fileBeans = batchBean.getDocument_Objects();
					for (BatchFileBean batchFileBean : fileBeans) {
						List<FileBean> files = batchFileBean.getFiles();
						for (FileBean fileBean : files) {
							Map<String, String> attMap = fileBean.getOtherAtt();
							String imageType = attMap.get("LOAN_DATA");
							if (Objects.nonNull(imageType) && !"".equals(imageType)) {
								// 页码
								busiFilePageNum++;
								// 批次文件
								logger.info("#######影像类型：" + imageType + "#####当前页码#####" + busiFilePageNum + "#######");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("#######查询当前批次的最大的页码异常#######" + e.getMessage());
			e.printStackTrace();
		}
		return busiFilePageNum;
	}

	/**
	 *
	 * 查询当前批次上传的信息 <br>
	 * 0.1:ludayong:2019年8月31日 上午11:09:54:新增 <br>
	 * @author ludayong
	 * @since 2019年8月31日 上午11:09:54
	 * @date 2019年8月31日 上午11:09:54
	 * @version 0.1
	 */
	public static Map<String, String> getUpdateBatchFileInfo(String resultMsg) {
		// 查询上传的产品信息
		Map<String, String> map = null;
		try {
			if (Objects.nonNull(resultMsg) && !"".equals(resultMsg)) {
				String batchStr = resultMsg.split(TransOptionKey.SPLITSYM)[1];
				List<BatchBean> batchBeans = XMLUtil.xml2list(XMLUtil.removeHeadRoot(batchStr), BatchBean.class);
				for (BatchBean batchBean : batchBeans) {
					BatchIndexBean indexBeans = batchBean.getIndex_Object();
					map = indexBeans.getCustomMap();
					logger.info("#######查询当前批次上传信息#######" + map == null ? "" : map.toString());
				}
			}
		} catch (Exception e) {
			logger.error("#######查询当前批次上传信息出现异常#######" + e.getMessage());
			e.printStackTrace();
		}
		return map;
	}
}
